<?php
class ApiController extends BpfController
{
  use ApiTrait {
    ApiTrait::okReturn as __okReturn;
  }
  public function __init()
  {
    $this->__apiInit();
    $this->setIni('dispatch.error_action', 'api');
    $playerModel = $this->getModel('player');
    $account = null;
    if (($playerid = $playerModel->checkLogin())) {
    // 未登录
      if (!($account = $playerModel->getPlayer($playerid))) {
        // 无效用户, 退出登录
        $this->toLoginPage();
      }
    }
    $this->account = $account;
    if (!$this->isLogin() ) {
      $this->toLoginPage();
    }
    $router = $this->getRouter();
    if (!in_array($router['action'], $this->allows ?? [])) {
      $this->account && $this->account->access();
    }
  }

  public function isLogin()
  {
    return isset($this->account);
  }


  public function toLoginPage()
  {
    $router = $this->getRouter();
    if (!in_array($router['action'], $this->allows ?? [])) {
      http_response_code(401);
      throw new Exception('请先登陆！！', 401);
    }
  }

  public function __formatPlayer($player)
  {
    return [
      'player_id' => $player->player_id ?? '',
      'nickname' => $player->nickname ?? '',
      'headimgurl' => $player->headimgurl ?? '',
      'sigin_seriate_times' => $player->sigin_seriate_times ?? '',
      'sigin_seriate_max_times' => $player->sigin_seriate_max_times,
      'flowers' => intval($player->flowers ?? 0 ),
      'has_store' => $player->hasStore(),
      'opengift' => $player->opengift
    ];
  }

  public function okReturn($result)
  {
    return $this->__okReturn([
      'data' => $result,
      'account' => $this->account ? $this->__formatPlayer($this->account): []
    ]);
  }


}
